<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;

class BusinessMember extends Authenticatable implements JWTSubject
{
	use HasDateTimeFormatter;
    use SoftDeletes;

    protected $hidden = [
        'password', 'created_at', 'updated_at', 'deleted_at'
    ];

    protected $cachePrefix = 'business_member_';

    protected $table = 'tinkle_business_member';

    public function login($username, $password)
    {
        // 登录验证，生成token
        return Auth::guard('api')->attempt([
            'username' => $username,
            'password' => $password,
        ]);
    }

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    // 模型关联 - 关联职位级别
    public function position()
    {
        return $this->hasOne(MemberPosition::class, 'id', 'position_id');
    }

    // 修改密码，hash校验 - 生成新密码 - 数据保存
    public function changePassword($oldPassword, $newPassword)
    {
        if (Hash::check($oldPassword, auth('api')->user()['password'])) {

            // 数据更新
            $member = $this->find(auth('api')->id());
            $member->password = Hash::make($newPassword);
            if (!$member->save()) {
                return false;
            }

            return true;
        }
        throw new \Exception('密码验证错误');
    }
}
